﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Ubiquity.Core.Security
{
    /// <summary>
    /// MD5加密
    /// </summary>
    public class Md5
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string Create(string str, int code = 32)
        {
            var result = "";
            using (var md5 = MD5.Create())
            {
                var temp = md5.ComputeHash(Encoding.ASCII.GetBytes(str));
                var strResult = BitConverter.ToString(temp);
                result = strResult.Replace("-", "");
            }
            string strEncrypt = string.Empty;
            if (code == 32)
            {
                strEncrypt = result;
            }
            else if (code == 16)
            {
                strEncrypt = result.Substring(8, 16);
            }
            else if (code == 8)
            {
                strEncrypt = result.Substring(0, 8);
            }


            return strEncrypt;
        }
    }
}
